<template>
  <el-dialog title="分配角色" :model-value="show" @close="$emit('hide')">
    <el-select
      multiple
      placeholder="请选择"
      v-model="list"
      style="width: 240px"
    >
      <el-option
        v-for="item in roles"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      >
      </el-option>
    </el-select>
    <template #footer>
      <el-button @click="cancel">取消</el-button>
      <el-button @click="confirm" type="primary">确定</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, watch } from "vue";
import {
  getRoleListApi,
  getRolesByUserIdApi,
  updateRolesUserApi,
} from "./api/api";

const props = defineProps({
  show: {
    type: Boolean,
    default: true,
  },
  id: {
    type: Number,
    default: 0,
  },
});
const emit = defineEmits(["hide"]);
const list = ref<number[]>([]);
const roles = ref<{ value: number; label: string }[]>([]);
getRoleListApi().then((res) => {
  if (res.code === 200) {
    roles.value = res.data.map((item) => ({
      label: item.name,
      value: item.id,
    }));
  }
});
// 取消
const cancel = () => {
  emit("hide");
};
watch(
  () => props.id,
  () => {
    getRolesByUserIdApi(props.id).then((res) => {
      if (res.code === 200) {
        list.value = res.data.map((item) => item.id);
      }
    });
  }
);
// 确定
const confirm = () => {
  ElMessageBox.confirm("确定要修改用户角色吗？", "修改用户角色", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      updateRolesUserApi(props.id, list.value).then((res) => {
        if (res.code === 200) {
          ElMessage.success("修改成功");
          emit("hide");
        }
      });
    })
    .catch(() => {});
};
</script>
<style lang="less" scoped></style>
